<!--签约方管理=> 联系人信息表 -->
<template >
  <div>
    <p class="type-item-title">联系人信息</p>
    <p v-if="!tableReadonly">
      <el-button type="primary" @click="openFormModal('add')">新增</el-button>
    </p>
    <table-list
      :tableData="tableData"
      :tableLabels="contactsTableLabels"
      :tableProps="contactsTableProps"
      :tableChangeBtns="contactsTableChangeBtns"
      :tableReadonly="tableReadonly"
      :activeBtn="tableBtnRule"
    ></table-list>
    <c-modal
      :type="contactsType"
      :editform="updateContactsForm"
      :visible.sync="contactstVisible"
      :hasImport="!!tableData.length"
      @onSave="editContact"
    ></c-modal>
  </div>
</template>
       

<script>
import api from "@/api/apiPath";
import tableList from "./tableList";
import contactsModal from "./contactsModal";
export default {
  components: {
    "table-list": tableList,
    "c-modal": contactsModal
  },
  data() {
    return {
      tableData: [],
      //联系人信息
      contactsTableChangeBtns: [
        //联系人操作按钮
        { label: "变更为主要联系人", type: "change", fn: this.changeContact },
        { label: "编辑", type: "edit", fn: this.openFormModal },
        { label: "删除", type: "dele", fn: this.deleContact }
      ],
      //联系人prop,//联系人表表头
      contactsTableProps: [
        "contactName",
        "contactPhone",
        "contactEmail",
        "add",
        "isImport",
        "operateName",
        "updateTime",
        "changeBtn"
      ],
      contactsTableLabels: [
        "姓名",
        "联系电话",
        "邮箱",
        "通信地址",
        "是否主要联系人",
        "更新人",
        "更新时间",
        "操作"
      ],
      contactstVisible: false, //联系人编辑框开关
      contactsType: "add", //联系人编辑状态
      contactsEditIdx: 0, //联系人当前编辑下标
      updateContactsForm: null, //联系人当前编辑数据
      tableReadonly: false //表格是否为只读状态
    };
  },
  methods: {
    //新增编辑联系人信息
    openFormModal(type, idx) {
      //记录当前需要编辑的数据
      if (type == "edit")
        this.updateContactsForm = JSON.parse(
          JSON.stringify(this.tableData[idx])
        );
      this.contactstVisible = true;
      //当前事件的状态
      this.contactsType = type;
      //当前编辑数据下标
      this.contactsEditIdx = idx;
    },

    //变更为主要联系人
    changeContact(type, idx) {
      if (this.typeStatus == "edit") {
        let {
          id,
          contactProvince,
          contactCity,
          contactCounty,
          contactAddress,
          contactName,
          contactPhone,
          contactEmail
        } = this.tableData[idx];
        let params = {
          contractUndersignType: this.typeId,
          insideId: this.insideId,
          id: id,
          input: {
            contactProvince: contactProvince,
            contactCity: contactCity,
            contactCounty: contactCounty,
            contactAddress: contactAddress,
            contactName: contactName,
            contactPhone: contactPhone,
            contactEmail: contactEmail,
            contactOne: 1
          }
        };
        this.axios.post(api.EDITCANTACTLIST, params).then(res => {
          if (res.data.code == 200) {
            this.loadContactList();
            this.$message({
              type: "success",
              message: "变更成功"
            });
          }
        });
      } else {
        this.tableData.forEach(data => {
          data.contactOneBool = false;
          data.isImport = "否";
        });
        if (idx === undefined) return;
        this.tableData[idx].contactOneBool = true;
        this.tableData[idx].isImport = "是";
      }
    },
    //格式化数据
    formatList(data) {
      let {
        contactProvince = "",
        contactCity = "",
        contactCounty = "",
        contactAddress = "",
        contactOne,
        operateTime,
        contactOneBool
      } = data;
      data.add =
        (contactProvince || "") +
        (contactCity || "") +
        (contactCounty || "") +
        (contactAddress || "");
      if (this.typeStatus != "add") {
        data.isImport = contactOne == 1 ? "是" : "否";
        data.contactOneBool = !!data.contactOne;
        data.updateTime = operateTime;
      } else {
        data.isImport = contactOneBool ? "是" : "否";
      }
      return data;
    },
    //解格式化数据
    unFormatList(data) {
      data.contactOne = data.contactOneBool ? 1 : 0;
      delete data.add;
      delete data.isImport;
      delete data.updateTime;
      delete data.contactOneBool;

      return data;
    },
    //加载联系人表（只在编辑和查看时使用）
    loadContactList() {
      let params = {
        contractUndersignType: this.typeId,
        contractUndersignId: this.insideId
      };
      this.axios.post(api.GETCANTACTLIST, params).then(res => {
        if (res.data.code == 200) {
          let lists = res.data.data;
          lists.forEach(list => {
            list = this.formatList(list);
          });
          this.tableData = lists;
        }
      });
    },
    //删除单条联系人
    deleContact(type, idx) {
      let thisList = this.tableData[idx];
      if (thisList.contactOne == 1 || thisList.contactOneBool) {
        this.$alert("主要联系人不能删除", { center: true })
          .then()
          .catch();
        return;
      }
      this.$confirm(`确定要删除联系人记录吗？`, "", {
        center: true,
        confirmButtonText: "确定",
        cancelButtonText: "取消"
      })
        .then(() => {
          if (this.typeStatus == "edit") {
            let id = thisList.id;
            let params = {
              contractUndersignType: this.typeId,
              insideId: this.insideId,
              id: id
            };
            this.axios.post(api.DELETECANTACTLIST, params).then(res => {
              if (res.data.code == 200) {
                this.loadContactList();
                this.$message({
                  type: "success",
                  message: "已删除"
                });
              }
            });
          } else {
            this.tableData.splice(idx, 1);
            this.$message({
              type: "success",
              message: "已删除"
            });
          }
        })
        .catch(() => {});
    },
    //添加/编辑单条联系人
    //(如果是新建管理列表状体下，只做本地数据更改）
    editContact(form) {
      if (this.typeStatus == "edit") {
        let thisApi = {
          edit: api.EDITCANTACTLIST,
          add: api.ADDCANTACTLIST
        };
        let doneMess = { edit: "编辑成功", add: "添加成功" };
        let params = {
          contractUndersignType: this.typeId,
          insideId: this.insideId,
          input: this.unFormatList(form)
        };
        let id = form.id;
        if (id) params.id = id;
        this.axios.post(thisApi[this.contactsType], params).then(res => {
          if (res.data.code == 200) {
            //关闭联系人弹窗
            this.contactstVisible = false;
            this.loadContactList();
            this.$message({
              type: "success",
              message: doneMess[this.contactsType]
            });
          }
        });
      } else {
        form = this.formatList(form);
        this.contactstVisible = false;
        if (form.contactOneBool) {
          this.changeContact();
        }
        if (this.contactsType == "add") {
          this.tableData.push(form);
        } else {
          this.$set(this.tableData, this.contactsEditIdx, form);
        }
      }
    },
    //按钮显示规则
    tableBtnRule(rowData, btns) {
      let [...newbtn] = btns;
      if (rowData.contactOneBool) {
        newbtn.shift();
      }
      return newbtn;
    },
    returnTabel() {
      let newTabelList = JSON.parse(JSON.stringify(this.tableData));
      newTabelList.forEach(data => {
        data = this.unFormatList(data);
      });
      return newTabelList;
    }
  },
  props: [
    "typeStatus", //当前签约方类型列表状态[add,edit]
    "insideId", //当前签约方类型列表id
    "typeId" //当前签约方类型id
  ],
  watch: {
    // tableData(){
    //      this.tableData.forEach(data=>{
    //         data = this.formatList(data);
    //     })
    // }
  },
  created() {
    //页面状态，新增无变化，编辑与查看请求联系人数据
    //查看状态时设置表格为只读状态
    switch (this.typeStatus) {
      case "add":
        this.tableReadonly = false;
        break;
      case "edit":
        this.tableReadonly = false;
        this.loadContactList();
        break;
      case "view":
        this.tableReadonly = true;
        this.loadContactList();
        break;
    }
  },
  destroyed() {},
  filters: {}
};
</script>

<style lang="stylus" scoped></style>
